#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
微信管理模块 - 统一管理小程序和公众号
"""

from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from typing import List, Optional, Dict, Any
import json
import logging
from datetime import datetime

from ..services.wechat_service import WeChatService
from ..models.wechat import MiniProgramInfo, OfficialAccountInfo, WeChatConfig

router = APIRouter(prefix="/api/wechat", tags=["微信管理"])

# 初始化微信服务
wechat_service = WeChatService()

# 数据模型
class WeChatAccountRequest(BaseModel):
    """微信账号请求模型"""
    name: str
    app_id: str
    app_secret: str
    account_type: str  # "miniprogram" 或 "official_account"
    description: Optional[str] = None

class WeChatAccountResponse(BaseModel):
    """微信账号响应模型"""
    id: int
    name: str
    app_id: str
    account_type: str
    status: str
    description: Optional[str] = None
    created_at: datetime
    updated_at: datetime

class MaterialRequest(BaseModel):
    """素材请求模型"""
    material_type: str  # "image", "voice", "video", "news"
    offset: int = 0
    count: int = 20

# ================================
# 微信账号管理
# ================================

@router.get("/accounts", response_model=List[WeChatAccountResponse])
async def get_wechat_accounts():
    """获取所有微信账号列表"""
    try:
        accounts = await wechat_service.get_all_accounts()
        return accounts
    except Exception as e:
        logging.error(f"获取微信账号列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取微信账号列表失败")

@router.post("/accounts", response_model=WeChatAccountResponse)
async def create_wechat_account(account: WeChatAccountRequest):
    """创建新的微信账号配置"""
    try:
        new_account = await wechat_service.create_account(
            name=account.name,
            app_id=account.app_id,
            app_secret=account.app_secret,
            account_type=account.account_type,
            description=account.description
        )
        return new_account
    except Exception as e:
        logging.error(f"创建微信账号失败: {e}")
        raise HTTPException(status_code=500, detail="创建微信账号失败")

@router.put("/accounts/{account_id}", response_model=WeChatAccountResponse)
async def update_wechat_account(account_id: int, account: WeChatAccountRequest):
    """更新微信账号配置"""
    try:
        updated_account = await wechat_service.update_account(
            account_id=account_id,
            **account.dict()
        )
        if not updated_account:
            raise HTTPException(status_code=404, detail="微信账号不存在")
        return updated_account
    except HTTPException:
        raise
    except Exception as e:
        logging.error(f"更新微信账号失败: {e}")
        raise HTTPException(status_code=500, detail="更新微信账号失败")

@router.delete("/accounts/{account_id}")
async def delete_wechat_account(account_id: int):
    """删除微信账号"""
    try:
        success = await wechat_service.delete_account(account_id)
        if not success:
            raise HTTPException(status_code=404, detail="微信账号不存在")
        return {"message": "微信账号删除成功"}
    except HTTPException:
        raise
    except Exception as e:
        logging.error(f"删除微信账号失败: {e}")
        raise HTTPException(status_code=500, detail="删除微信账号失败")

# ================================
# Access Token 管理
# ================================

@router.get("/accounts/{account_id}/token")
async def get_access_token(account_id: int):
    """获取指定账号的Access Token"""
    try:
        token_info = await wechat_service.get_access_token(account_id)
        return {
            "access_token": token_info["access_token"],
            "expires_in": token_info["expires_in"],
            "expires_at": token_info["expires_at"]
        }
    except Exception as e:
        logging.error(f"获取Access Token失败: {e}")
        raise HTTPException(status_code=500, detail="获取Access Token失败")

@router.post("/accounts/{account_id}/token/refresh")
async def refresh_access_token(account_id: int):
    """刷新指定账号的Access Token"""
    try:
        token_info = await wechat_service.refresh_access_token(account_id)
        return {
            "message": "Access Token刷新成功",
            "access_token": token_info["access_token"],
            "expires_at": token_info["expires_at"]
        }
    except Exception as e:
        logging.error(f"刷新Access Token失败: {e}")
        raise HTTPException(status_code=500, detail="刷新Access Token失败")

# ================================
# 素材管理（公众号）
# ================================

@router.get("/accounts/{account_id}/materials")
async def get_materials(account_id: int, material_request: MaterialRequest = Depends()):
    """获取指定账号的素材列表"""
    try:
        materials = await wechat_service.get_materials(
            account_id=account_id,
            material_type=material_request.material_type,
            offset=material_request.offset,
            count=material_request.count
        )
        return materials
    except Exception as e:
        logging.error(f"获取素材列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取素材列表失败")

@router.get("/accounts/{account_id}/materials/count")
async def get_material_count(account_id: int):
    """获取指定账号的素材统计"""
    try:
        count_info = await wechat_service.get_material_count(account_id)
        return count_info
    except Exception as e:
        logging.error(f"获取素材统计失败: {e}")
        raise HTTPException(status_code=500, detail="获取素材统计失败")

# ================================
# 用户管理
# ================================

@router.get("/accounts/{account_id}/users")
async def get_users(account_id: int, next_openid: Optional[str] = None):
    """获取指定账号的用户列表"""
    try:
        users = await wechat_service.get_users(account_id, next_openid)
        return users
    except Exception as e:
        logging.error(f"获取用户列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取用户列表失败")

@router.get("/accounts/{account_id}/users/{openid}")
async def get_user_info(account_id: int, openid: str):
    """获取指定用户的详细信息"""
    try:
        user_info = await wechat_service.get_user_info(account_id, openid)
        return user_info
    except Exception as e:
        logging.error(f"获取用户信息失败: {e}")
        raise HTTPException(status_code=500, detail="获取用户信息失败")

# ================================
# 菜单管理（公众号）
# ================================

@router.get("/accounts/{account_id}/menu")
async def get_menu(account_id: int):
    """获取公众号菜单"""
    try:
        menu = await wechat_service.get_menu(account_id)
        return menu
    except Exception as e:
        logging.error(f"获取菜单失败: {e}")
        raise HTTPException(status_code=500, detail="获取菜单失败")

@router.post("/accounts/{account_id}/menu")
async def create_menu(account_id: int, menu_data: Dict[str, Any]):
    """创建公众号菜单"""
    try:
        result = await wechat_service.create_menu(account_id, menu_data)
        return {"message": "菜单创建成功", "result": result}
    except Exception as e:
        logging.error(f"创建菜单失败: {e}")
        raise HTTPException(status_code=500, detail="创建菜单失败")

@router.delete("/accounts/{account_id}/menu")
async def delete_menu(account_id: int):
    """删除公众号菜单"""
    try:
        result = await wechat_service.delete_menu(account_id)
        return {"message": "菜单删除成功", "result": result}
    except Exception as e:
        logging.error(f"删除菜单失败: {e}")
        raise HTTPException(status_code=500, detail="删除菜单失败")

# ================================
# 统计数据
# ================================

@router.get("/accounts/{account_id}/statistics")
async def get_statistics(account_id: int, start_date: str, end_date: str):
    """获取账号统计数据"""
    try:
        stats = await wechat_service.get_statistics(account_id, start_date, end_date)
        return stats
    except Exception as e:
        logging.error(f"获取统计数据失败: {e}")
        raise HTTPException(status_code=500, detail="获取统计数据失败")

# ================================
# 健康检查
# ================================

@router.get("/health")
async def health_check():
    """微信管理模块健康检查"""
    return {
        "status": "healthy",
        "module": "wechat_management",
        "timestamp": datetime.now().isoformat(),
        "version": "1.0.0"
    }
